import time
from fpioa_manager import fm
from Maix import GPIO

# 定义超声波传感器的触发引脚和回响引脚
trig_pin = 0
echo_pin = 1

# 将GPIO口初始化为输入/输出模式
fm.register(trig_pin, fm.fpioa.GPIO0)
fm.register(echo_pin, fm.fpioa.GPIO1)
trig = GPIO(GPIO.GPIO0, GPIO.OUT)
echo = GPIO(GPIO.GPIO1, GPIO.IN)


def measure_distance():
    # 发送触发信号
    trig.value(0)
    time.sleep_ms(2)
    trig.value(1)
    time.sleep_us(10)
    trig.value(0)

    # 等待回响信号
    while echo.value() == 0:
        pass
    t1 = time.ticks_us()

    while echo.value() == 1:
        pass
    t2 = time.ticks_us()

    # 计算距离（单位：厘米）
    duration = t2 - t1
    distance = duration * 0.034 / 2
    return distance


while True:
    distance = measure_distance()
    print("Distance: %.2f cm" % distance)
    time.sleep(1)
